import axios from 'axios';
import {getToken, setToken} from './auth.js';
import {ElMessage} from 'element-plus';
import router from '@/router';
import Utils from './Utils.js';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// 创建axios实例
const service = axios.create({
    baseURL: '/api', timeout: 20000
});
// 请求拦截器
service.interceptors.request.use(config => {
    // noinspection JSUnresolvedReference
    if (config.token) {
        config.headers['Authorization'] = `Bearer ${getToken()}`;
    }
    return config;
}, error => {
    console.error('request error:', error);
    return Promise.reject(error);
});
// 响应拦截器
service.interceptors.response.use(res => {
    const {config: {download}, data} = res;
    if (download) return data;
    const {code, msg} = data;
    if (code === 200) return data;
    switch (code) {
        case 401:
            setToken(null);
            requestAnimationFrame(() => router.push('/login'));
            break;
        default:
            ElMessage.error(msg);
            break;
    }
    return Promise.reject(msg);
}, error => {
    console.error('response error:', error);
    if (error.message === 'Network Error') {
        requestAnimationFrame(() => router.push('/login'));
    }
    return Promise.reject(error);
});
export default {
    get(url, params = {}) {
        const cloneData = JSON.parse(JSON.stringify(params));
        Object.keys(cloneData).forEach(key => {
            if (params[key] instanceof Date) {
                cloneData[key] = Utils.convertDateToString(params[key]);
            }
        });
        return service.get(url, {
            params: cloneData, token: true
        });
    }, getWithoutToken(url, params) {
        return service.get(url, {
            params
        });
    }, post(url, data = {}) {
        const cloneData = JSON.parse(JSON.stringify(data));
        Object.keys(cloneData).forEach(key => {
            if (data[key] instanceof Date) {
                cloneData[key] = Utils.convertDateToString(data[key]);
            }
        });
        return service.post(url, cloneData, {token: true});
    }, postWithoutToken(url, data = {}) {
        return service.post(url, data, {token: false});
    }, put(url, data = {}) {
        const cloneData = JSON.parse(JSON.stringify(data));
        Object.keys(cloneData).forEach(key => {
            if (data[key] instanceof Date) {
                cloneData[key] = Utils.convertDateToString(data[key]);
            }
        });
        return service.put(url, cloneData, {token: true});
    }, delete(url, ids) {
        const idsString = ids.join(',');
        return service.delete(`${url}?ids=${idsString}`, {
            token: true
        });
    },
    downloadFile(url, params = {}, fileName) {
        return (service.get(url, {
            responseType: 'blob', token: true, download: true, params
        }).then(res => {
            const link = document.createElement('a');
            link.href = URL.createObjectURL(res);
            link.setAttribute('download', fileName || Utils.getFileNameFromURL(url));
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }));
    },
    previewFile(url) {
        return service.get(url, {
            responseType: 'blob', token: true, download: true
        });
    }
};